package com.athuiju.fenxiaoback.controller.front;


import com.athuiju.fenxiaoback.entity.UcenterMember;
import com.athuiju.fenxiaoback.entity.vo.*;
import com.athuiju.fenxiaoback.service.MsmService;
import com.athuiju.fenxiaoback.service.UcenterMemberService;
import com.athuiju.fenxiaoback.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Api(description = "<font style='color:red'>登录---注册---忘记密码</font>",tags = "<font style='color:red'>登录---注册---忘记密码</font>")

@RestController
@RequestMapping("/fenxiaoback01/ucenter-member")
public class MemberFrontController {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Autowired
    MsmService msmService;

    @ApiOperation(value = "判断手机号---是否已注册")
    @GetMapping("isRegist/{phone}")
    public R isRegist(@ApiParam("示例：1xxxxxxxxxxx")@PathVariable(required = true) String phone){
        if (StringUtils.isEmpty(phone)){
            return R.error().put("msg","请输入手机号码");
        }
        if(phone.length()!=11){
            return R.error().put("msg","手机号码长度不正确");
        }
        //if (!PhoneNumUtil.isChinaPhoneNum(phone)){
        //    return R.error().put("msg","手机号码格式");
        //}
        QueryWrapper<UcenterMember> memberQueryWrapper=new QueryWrapper<>();
        memberQueryWrapper.select("mobile");
        List<UcenterMember> list = memberService.list(memberQueryWrapper);
        boolean flag=false;
        for (UcenterMember p : list) {
            if (phone.equals(p.getMobile())){
                flag=true;
                break;
            }
        }
        return  flag ? R.error().put("code",500).put("msg","此号码已注册") :R.error().put("msg","未注册").put("code",200);
    }



    @ApiOperation(value = "未登录状态---修改密码")
    @PostMapping("notLoginUpdatePassWord")
    public R notLoginUpdatePassWord(@RequestBody NotLoginUpdatePasswordVo notLoginUpdatePasswordVo){

        //1.检查当前号码是否注册过
        String phone = notLoginUpdatePasswordVo.getPhone();
        List<UcenterMember> members = memberService.list(new QueryWrapper<UcenterMember>().eq("mobile", phone));
        if(members == null || members.size()==0){
            return R.error().put("msg","此号码未注册，先去注册");
        }
        //System.out.println(updatePasswordVo);
        String againPassword = notLoginUpdatePasswordVo.getAgainPassword();
        String newPassword=notLoginUpdatePasswordVo.getNewPassword();

        if(!StringUtils.isEmpty(againPassword) && !StringUtils.isEmpty(newPassword)){
            if (againPassword.equalsIgnoreCase(newPassword)){
                //String memberid = JwtUtils.getMemberIdByJwtToken(request);
                //UcenterMember member = memberService.getById(memberid);
                //根据电话号码获取用户
                UcenterMember member = memberService.getOne(new QueryWrapper<UcenterMember>().eq("mobile", phone));


                member.setPassword(MD5.encrypt(notLoginUpdatePasswordVo.getNewPassword()));
                memberService.updateById(member);
                return R.ok().put("msg","密码设置成功");
            }
        }
        return R.error().put("code","500").put("msg","密码设置失败,检查新旧密码");
    }




    //登录
    @ApiOperation(value = "校验验证码")
    @PostMapping("verifyCode")
    public R loginUser(@RequestBody VerifyCodeVo verifyCodeVo) {

        String phone = verifyCodeVo.getPhone();
        String code = verifyCodeVo.getCode();

        String rediscode = redisTemplate.opsForValue().get(phone);
        System.out.println(phone+"-------"+rediscode);
        if (rediscode==null || rediscode.equals("")){
            return R.error().put("msg","请重新获取验证码").put("code",500);
        }

        if (code!=null && !code.equals("")){
            if (code.equalsIgnoreCase(rediscode)){
                return R.ok().put("msg","验证码校验通过").put("code",200);
            }else{
                return R.error().put("msg","验证码错误").put("code",500);
            }
        }

        return R.error().put("msg","验证码错误").put("code",500);
    }


    @ApiOperation(value = "忘记秘密---获取验证码")
    @GetMapping("sendSMS/{phone}")
    public R sendSMS(@ApiParam("示例：1xxxxxxxxxxx")@PathVariable String phone){

        List<UcenterMember> members = memberService.list(new QueryWrapper<UcenterMember>().eq("mobile", phone));
        if (members==null || members.size()==0){
            return R.error().put("msg","此号码未注册，发送验证码失败");
        }


        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();//生成四位的随机数
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().put("msg","短信发送失败");
        }
    }

    @ApiOperation(value = "注册---获取验证码")
    @GetMapping("registSendSMS/{phone}")
    public R registSendSMS(@ApiParam("示例：1xxxxxxxxxxx")@PathVariable String phone){

        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();//生成四位的随机数
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().put("msg","短信发送失败");
        }
    }



    //登录
    @ApiOperation(value = "登录")
    @PostMapping("login")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = String.class)
    })
    public R loginUser(@RequestBody UcenterMemberVO membervo) {
        //member对象封装手机号和密码
        //调用service方法实现登录
        //返回token值，使用jwt生成


        String token = memberService.login(membervo);
        return R.ok().put("token",token);
    }



    @ApiOperation(value = "注册")
    @PostMapping("register")
    public R register(@ApiParam("电话号码不能重复") @RequestBody RegisterVo registerVo){

        memberService.register(registerVo);
        return R.ok();
    }



}
